/*
 * @Author: 刘思思
 * @Date: 2024-12-02 20:18:27
 * @LastEditors: 刘思思
 * @LastEditTime: 2024-12-02 20:18:36
 * @FilePath: /AdvertisingMachine/main/src/configRequest.c
 * @Description:
 *
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved.
 */
#include "configRequest.h"

size_t configCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
    size_t realsize = size * nmemb;
    // 这里可以处理获取到的数据，比如存储到文件或者其他操作
    char *result = (char *)contents;
    printf("%s\n", result);

    cJSON *jsonstr = cJSON_Parse(result);
    if (jsonstr != NULL)
    {
        cJSON *successRoot = cJSON_GetObjectItemCaseSensitive(jsonstr, "success");
        cJSON *codeRoot = cJSON_GetObjectItemCaseSensitive(jsonstr, "code");
        cJSON *messageRoot = cJSON_GetObjectItemCaseSensitive(jsonstr, "message");

        if (cJSON_IsTrue(successRoot))
        {
            printf("%s\n", messageRoot->valuestring);
        }
        else
        {
            perror("网络异常\n");
        }
    }
    return realsize;
}
void sendConfigRequest()
{
    // 1.读取当前文件目录下面的config.ini  获取 devinfo_path 地址
    GKeyFile *configiniPath = g_key_file_new();
    if (!g_key_file_load_from_file(configiniPath, "./config.ini", G_KEY_FILE_NONE, NULL))
    {
        g_warning("load config.ini error!");
        return -1;
    }
    gchar *path = g_key_file_get_string(configiniPath, "config", "devinfo_path", NULL);
    g_key_file_free(configiniPath);
    // 2.去devinfo_path指定的文件中读取 ip 和 地址
    GKeyFile *configPath = g_key_file_new();
    if (!g_key_file_load_from_file(configPath, path, G_KEY_FILE_NONE, NULL))
    {
        g_warning("load config.ini error!");
        return -1;
    }
    gchar *gatewayIp = g_key_file_get_string(configPath, "config", "gatewayIp", NULL);
    gchar *location = g_key_file_get_string(configPath, "config", "location", NULL);
    g_key_file_free(configPath);
    char *url = "http://%s/config.json?sn=%s&location=%s";
    char *realUrl = calloc(1, 100);
    sprintf(realUrl, url, gatewayIp, location);
    printf("request address:%s\n", realUrl);
    // 发送一个get请求
    // http://ip/config.json?sn=1205556&location=sasada
    sendGetRequest(realUrl, configCallback);
}
